package com.talos.ums.service.usercompany;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.usercompany.vo.UmsUserCompanyPageReqVO;
import com.talos.ums.controller.admin.usercompany.vo.UmsUserCompanySaveReqVO;
import com.talos.ums.dal.dataobject.usercompany.UmsUserCompanyDO;
import com.talos.ums.dal.mysql.usercompany.UmsUserCompanyMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户货主关系表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserCompanyServiceImpl implements UmsUserCompanyService {

    @Resource
    private UmsUserCompanyMapper userCompanyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserCompany(UmsUserCompanySaveReqVO createReqVO) {
        // 插入
        UmsUserCompanyDO userCompany = BeanUtils.toBean(createReqVO, UmsUserCompanyDO.class);
        userCompanyMapper.insert(userCompany);
        // 返回
        return userCompany.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserCompany(UmsUserCompanySaveReqVO updateReqVO) {
        // 校验存在
        validateUserCompanyExists(updateReqVO.getId());
        // 更新
        UmsUserCompanyDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserCompanyDO.class);
        userCompanyMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserCompany(Long id) {
        // 校验存在
        validateUserCompanyExists(id);
        // 删除
        userCompanyMapper.deleteById(id);
    }

    private void validateUserCompanyExists(Long id) {
        if (userCompanyMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserCompanyDO getUserCompany(Long id) {
        return userCompanyMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserCompanyDO> getUserCompanyPage(UmsUserCompanyPageReqVO pageReqVO) {
        return userCompanyMapper.selectPage(pageReqVO);
    }

}
